package com.ciaojian.websocket.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Atlakyn
 */
@Log4j2(topic = "websocket")
@Component
@ServerEndpoint("/{clientId}")
public class MyWebSocket {

    /**
     * 在线人数
     */
    public static int onlineNumber = 0;

    /**
     * 以id为key，MyWebSocket为对象保存起来
     */
    private static Map<Integer, MyWebSocket> clients = new ConcurrentHashMap<>();

    /**
     * 会话
     */
    private Session session;

    /**
     * 用户名称
     */
    private int clientId;

    /**
     * 建立连接
     */
    @OnOpen
    public void onOpen(@PathParam(value = "clientId") int clientId, Session session) {
        onlineNumber++;
        clients.put(clientId, this);
        this.clientId = clientId;
        this.session = session;
        log.info(">>>{}建立了连接>>>", clientId);
    }

    @OnError
    public void onError(Throwable error) {
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("clientId") int clientId) {
        clients.remove(clientId);
        onlineNumber--;
        log.info(">>>{}关闭了连接>>>", clientId);
    }

    /**
     * 收到客户端的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws JsonProcessingException {
        // 回应客户端

    }

    /**
     * 发送消息给指定用户
     *
     * @param message   消息
     * @param toTableId 指定用户
     */
    public void sendMessageTo(String message, int toTableId) throws NullPointerException {
        MyWebSocket item = clients.get(toTableId);
        item.session.getAsyncRemote().sendText(message);
    }

    public void sendMessageAll(String message) throws IOException {
        for (MyWebSocket item : clients.values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineNumber;
    }
}
